package com.example.utils;

import org.springframework.util.StringUtils;

import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by hldev on 17-2-8.
 */
public class AuthToken {

    private static ThreadLocal<AuthToken> authTokenThreadLocal = new ThreadLocal<>();

    public final String userName;

    public final Integer id;


    private AuthToken(String userName, Integer id) {
        this.userName = userName;
        this.id = id;
    }

    static public AuthToken create(String userName, Integer id) {
        AuthToken authToken = new AuthToken(userName, id);
        authTokenThreadLocal.set(authToken);
        return authToken;
    }

    @Deprecated
    public static AuthToken getAndSetFromThreadLocal(AuthToken token) {
        AuthToken authToken = authTokenThreadLocal.get();
        if (authToken == null) {
            authTokenThreadLocal.set(token);
            authToken = token;
        }
        return authToken;
    }


    /**
     * 从ThreadLocal中获取AuthToken实例
     *
     * @return 返回AuthToken的Optional包装对象
     */
    public static Optional<AuthToken> getFromThreadLocal() {
        return Optional.ofNullable(authTokenThreadLocal.get());
    }

    /**
     * 从ThreadLocal中删除AuthToken实例
     */
    public static void removeOnThreadLocal() {
        authTokenThreadLocal.remove();
    }
}
